package IdManagement;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.Properties;

public class DBUtil {
	private static Connection con;
	
	public static Connection getConnection() throws IOException, SQLException{
		if (con!=null) {
			return con;
		}
		Properties pro=new Properties();
		try(InputStream in=Files.newInputStream(Paths.get("info.properties"))){
			pro.load(in);
		}	
		String driver=pro.getProperty("jdbc.driver");
		if (driver!=null) System.setProperty("jdbc.driver", driver);
		
		String url=pro.getProperty("jdbc.url");
		String username=pro.getProperty("jdbc.username");
		String password=pro.getProperty("jdbc.password");
		
		con = DriverManager.getConnection(url,username,password);
		return con;
	}
	
	public static int getCount(String tableName) throws SQLException, IOException {
		if (con==null)
			con=DBUtil.getConnection();
		Statement state = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		ResultSet rs=state.executeQuery("select count(*) totalCount from "+tableName);
		int rowCount = 0;
		if(rs.next()) {
			rowCount=rs .getInt("totalCount");
		}
		return rowCount;
	}
	public static void close() {
		if (con==null) {
			return;
		}
		
		try {
			con.close();
		} catch (SQLException e) {
			
		}finally {
			con=null;
		}
	}
	
	public static LinkedList<String> getAllTableName() throws IOException, SQLException{
		if (con==null) {
			con=DBUtil.getConnection();
		}
		
		LinkedList<String> list=new LinkedList<>();
		Statement state=con.createStatement();
		ResultSet rs=state.executeQuery("show tables");
		while(rs.next()) {
			list.add(rs.getString(1));
		}
		return list;
	}
	
	public static void createTable(String tableName,String values) throws IOException, SQLException {
		if (con==null)
			con=DBUtil.getConnection();
		String sql="create table %s (%s)";
		con.createStatement().executeLargeUpdate(String.format(sql,tableName,values));
	}
	
	public static void main(String...args) {
		try {
			DBUtil.createTable("alluser_a", "xxx int unsigned not null auto_increment primary key,id varchar(20) not null unique");
			getAllTableName().stream().forEach(System.out::println);
		} catch (IOException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
